package cn.akwangl.socket.aio.simple;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;

/**
 * 一个简单AIO实现的socket.
 *
 * @author 阿坤同学
 * @date 2022/6/24 21:57
 * @since 0.0.6
 */
@Slf4j
public class AIOSimpleService {

    public static final int SERVER_PORT = 7000;
    public static final String SERVER_ADDRESS = "localhost";
    private AsynchronousServerSocketChannel serverSocketChannel;

    public void start() {
        try {
            serverSocketChannel = AsynchronousServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT));

            while (true) {
                serverSocketChannel.accept(serverSocketChannel, new AcceptHandler());
                System.in.read();
            }
        } catch (IOException e) {
            log.error("service 创建失败", e);
        } finally {
            try {
                serverSocketChannel.close();
            } catch (IOException e) {
                log.error("service 关闭失败", e);
            }
        }
    }

    public static void main(String[] args) {
        AIOSimpleService service = new AIOSimpleService();
        service.start();
    }
}
